/**
 * Created by Administrator on 2017/8/28.
 */
let variable = require('../data/variable.js');
let gameData = require('../util/gameData.js');
let mem = require('../util/mem.js');
let util = require('../util/util.js');
let rpc = require('../util/rpc.js');
let game = require('./game.js');
let save = require('./save.js');
let log = require('../util/log.js');

let method = module.exports;

method.create = function (data) {
    let result = {};
    if (!data) {
        result.code = 101;
        return result;
    }

    let lv = data.lv;
    let inGame = false;

    let user = [];
    for (let i = 0, len = data.user.length; i < len; i++) {
        let j = Math.floor(Math.random() * data.user.length);
        user[i] = data.user[j];
        data.user.splice(j, 1);
    }
    //let user = data.user;

    for (let i in user) {
        if (mem.gamePlayers[user[i].id]) {
            inGame = true;
            if (!result.inGameId) {
                result.inGameId = {};
            }
            result.inGameId[user[i].id] = {};
            result.inGameId[user[i].id].local = mem.gamePlayers[user[i].id].local;
            result.inGameId[user[i].id].gameId = mem.gamePlayers[user[i].id].gameId;
            try {
                result.inGameId[user[i].id].gameType = gameData.d.gameLv[mem.games[mem.gamePlayers[user[i].id].gameId].lv].type;
            } catch (e) {
                result.inGameId[user[i].id].gameType = 1;
                log.e('game/room.js line 43 error', user[i].id, mem.gamePlayers[user[i].id], mem.games[mem.gamePlayers[user[i].id].gameId]);
            }
        }
    }
    if (inGame) {
        result.code = 102;
        return result;
    }

    let gameId = makeGameId();

    let ids = [];
    let player = {};
    for (let i in user) {
        setPlayer(user[i], gameId, i, gameData.d.gameLv[lv].coinType);
        if (user[i].robot) {
            mem.gamePlayers[user[i].id].robot = true;
            mem.gamePlayers[user[i].id].line = 'on';
            mem.gamePlayers[user[i].id].inRoom = true;
            mem.gamePlayers[user[i].id].ready = true;
        } else {
            setPlayerJoin(user[i].id);
        }
        ids.push(user[i].id);
        player[user[i].id] = i;
    }

    setGame(gameId, ids, lv, gameData.d.gameLv[lv].type);

    result.code = 200;
    result.key = gameId;
    result.player = player;
    result.host = util.getServerInfo('local');
    result.port = util.getServerInfo('port');
    return result;
};
method.happy = function (data) {
    let result = {};
    if (!data) {
        result.code = 101;
        return result;
    }

    let lv = data.lv;
    let inGame = false;

    let user = [];
    for (let i = 0, len = data.user.length; i < len; i++) {
        let j = Math.floor(Math.random() * data.user.length);
        user[i] = data.user[j];
        data.user.splice(j, 1);
    }
    //let user = data.user;

    for (let i in user) {
        if (mem.gamePlayers[user[i].id]) {
            inGame = true;
            if (!result.inGameId) {
                result.inGameId = {};
            }
            result.inGameId[user[i].id] = {};
            result.inGameId[user[i].id].local = mem.gamePlayers[user[i].id].local;
            result.inGameId[user[i].id].gameId = mem.gamePlayers[user[i].id].gameId;
            try {
                result.inGameId[user[i].id].gameType = gameData.d.gameLv[mem.games[mem.gamePlayers[user[i].id].gameId].lv].type;
            } catch (e) {
                result.inGameId[user[i].id].gameType = 1;
                log.e('game/room.js line 114 error', user[i].id, mem.gamePlayers[user[i].id], mem.games[mem.gamePlayers[user[i].id].gameId]);
            }
        }
    }
    if (inGame) {
        result.code = 102;
        return result;
    }

    let gameId = makeGameId();

    let ids = [];
    let player = {};
    for (let i in user) {
        setPlayer(user[i], gameId, i, gameData.d.gameLv[lv].coinType);
        if (user[i].robot) {
            mem.gamePlayers[user[i].id].robot = true;
            mem.gamePlayers[user[i].id].line = 'on';
            mem.gamePlayers[user[i].id].inRoom = true;
            mem.gamePlayers[user[i].id].ready = true;
        } else {
            setPlayerJoin(user[i].id);
        }
        ids.push(user[i].id);
        player[user[i].id] = i;
    }

    setGame(gameId, ids, lv, gameData.d.gameLv[lv].type);

    result.code = 200;
    result.key = gameId;
    result.player = player;
    result.host = util.getServerInfo('local');
    result.port = util.getServerInfo('port');
    return result;
};
method.custom = function (data) {
    let result = {};
    if (!data.id) {
        result.code = 101;
        return result;
    }
    if (mem.gamePlayers[data.id]) {
        result.code = 102;
        result.gameId = mem.gamePlayers[data.id].gameId;
        result.local = mem.gamePlayers[data.id].local;
        //result.gameType = gameData.d.gameLv[mem.games[mem.gamePlayers[data.id].gameId].lv].type;
        return result;
    }

    let id = data.id;
    let password = (!data.password) ? data.password : null;
    let rounds = (!data.rounds) ? data.rounds : 6;
    let gameId = makeGameId();

    setPlayer(data, gameId, 0, gameData.d.gameLv[0].coinType);
    setGame(gameId, [id], 0, gameData.d.gameLv[0].type);
    setRecruit(gameId, data.id, data.name, data.avatar, data.bluedId);
    mem.games[gameId].password = password;
    mem.games[gameId].rounds = rounds;
    mem.games[gameId].owerId = id;

    result.key = gameId;
    result.local = 0;
    result.code = 200;
    return result;
};
method.follow = function (data) {
    let result = {};
    if (!data.id && !data.gameId) {
        result.code = 101;
        return result;
    }
    if (mem.gamePlayers[data.id]) {
        result.code = 102;
        result.gameId = mem.gamePlayers[data.id].gameId;
        result.local = mem.gamePlayers[data.id].local;
        result.gameType = gameData.d.gameLv[mem.games[mem.gamePlayers[data.id].gameId].lv].type;
        return result;
    }
    if (!mem.games[data.gameId]) {
        result.code = 103;
        return result;
    }
    if (mem.games[data.gameId].id.length >= 3) {
        result.code = 104;
        return result;
    }
    if (mem.games[data.gameId].password && mem.games[data.gameId].password != data.password) {
        result.code = 105;
        return result;
    }

    let key = data.gameId;
    let id = data.id;
    let locals = [false, false, false];
    for (let i in mem.games[key].id) {
        let idx = mem.games[key].id[i];
        locals[mem.gamePlayers[idx].local] = true;
    }
    let local = 0;
    for (let i in locals) {
        if (locals[i] == false) {
            local = i;
            break;
        }
    }

    setPlayer(data, key, local, gameData.d.gameLv[mem.games[data.gameId].lv].coinType);

    mem.games[key].id.push(id);

    result.key = key;
    result.local = local;
    result.code = 200;
    return result;
};
method.arena = function (data) {
    let result = {};
    if (!data) {
        result.code = 101;
        return result;
    }

    let lv = data.lv;
    let mode = data.mode;
    let inGame = false;

    let user = [];
    for (let i = 0, len = data.user.length; i < len; i++) {
        let j = Math.floor(Math.random() * data.user.length);
        user[i] = data.user[j];
        data.user.splice(j, 1);
    }
    //let user = data.user;

    for (let i in user) {
        if (mem.gamePlayers[user[i].id]) {
            inGame = true;
            if (!result.inGameId) {
                result.inGameId = {};
            }
            result.inGameId[user[i].id] = {};
            result.inGameId[user[i].id].local = mem.gamePlayers[user[i].id].local;
            result.inGameId[user[i].id].gameId = mem.gamePlayers[user[i].id].gameId;
            try {
                result.inGameId[user[i].id].gameType = gameData.d.gameLv[mem.games[mem.gamePlayers[user[i].id].gameId].lv].type;
            } catch (e) {
                result.inGameId[user[i].id].gameType = 1;
                log.e('game/room.js line 261 error', user[i].id, mem.gamePlayers[user[i].id], mem.games[mem.gamePlayers[user[i].id].gameId]);
            }
        }
    }
    if (inGame) {
        result.code = 102;
        return result;
    }

    let gameId = makeGameId();

    let ids = [];
    let player = {};
    for (let i in user) {
        setPlayer(user[i], gameId, i, gameData.d.gameLv[lv].coinType);
        setPlayerJoin(user[i].id);

        ids.push(user[i].id);
        player[user[i].id] = i;
    }

    setGame(gameId, ids, lv, gameData.d.gameLv[lv].type);
    mem.games[gameId].mode = mode;

    result.code = 200;
    result.key = gameId;
    result.player = player;
    result.host = util.getServerInfo('local');
    result.port = util.getServerInfo('port');
    return result;
};


function setGame(gameId, ids, lv, type) {
    let createTime = Date.now();
    mem.games[gameId] = {};
    mem.games[gameId].createTime = createTime;
    mem.games[gameId].gameId = gameId;
    mem.games[gameId].lv = lv;
    mem.games[gameId].id = ids;
    mem.games[gameId].type = type; 

    log.game(gameId, ids, lv);

    let param = {};
    param.gameId = gameId;
    param.lv = lv;
    param.createTime = createTime;
    param.serverId = util.getServerInfo('id');
    rpc.dc.send('addGame', param);
}

function setRecruit(gameId, id, name, avatar, bluedId) {
    let param = {};
    param.gameId = gameId;
    param.id = id;
    param.name = name;
    param.avatar = avatar;
    param.bluedId = bluedId;
    rpc.dc.send('addRecruit', param);
}

function setPlayer(user, gameId, local,coinType) {
    mem.gamePlayers[user.id] = {};
    mem.gamePlayers[user.id].id = user.id;
    mem.gamePlayers[user.id].cid = null;
    mem.gamePlayers[user.id].uuid = null;
    mem.gamePlayers[user.id].local = local;
    mem.gamePlayers[user.id].gameId = gameId;
    mem.gamePlayers[user.id].line = null;
    mem.gamePlayers[user.id].inRoom = false;
    mem.gamePlayers[user.id].ready = false;
    mem.gamePlayers[user.id].name = user.name;
    mem.gamePlayers[user.id].avatar = user.avatar;
    //mem.gamePlayers[user.id].score = user.score;
    //mem.gamePlayers[user.id].gold = user.gold;
    mem.gamePlayers[user.id].coin = user[coinType];
    mem.gamePlayers[user.id].bluedId = user.bluedId;
    mem.gamePlayers[user.id].weixinId = user.weixinId;
    mem.gamePlayers[user.id].showCard = user.showCard;

    if (user.robot) {
        save.setRobot(user.id, gameId);
    } else {
        save.setGameId(user.id, gameId);
        //let param = {};
        //param.userId = user.id;
        //rpc.dc.send('taskList', param, function (data) {
        //    mem.gamePlayers[user.id].task = data;
        //});
    }
}

function setPlayerJoin(userId) {
    //mem.gamePlayers[userId].timeoutJoin = setTimeout(function () {
    //    game.join({'userId': userId});
    //}, (gameData.d.config.joinTimeout * 1000));
}

function makeGameId() {
    let gameId;
    while (true) {
        let s = (new Date).getMilliseconds();
        if (s < 10) {
            s = '00' + s;
        } else if (s < 100) {
            s = '0' + s;
        }
        let key = util.getServerInfo('id') + '' + s + '' + (Math.floor(Math.random() * 8999) + 1000);
        key = parseInt(key).toString(16);
        if (!mem.games[key]) {
            gameId = key;
            break;
        }
    }
    return gameId;
}